package com.banciyuan.bcywebview.utils.update;

import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.app.BaseApplication;
import com.banciyuan.bcywebview.base.view.dialog.UpdateDialog;
import com.banciyuan.bcywebview.utils.file.FileUtils;
import com.banciyuan.bcywebview.utils.http.NetUtils;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.sys.SystemUtils;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;

import java.io.File;

/**
 * @author hfxt2008
 *         用于检测是否有新版本出现，并自动下载的工具类，用到了小米检测更新的SDK
 *         PS:现在是强制升级的。
 */
public class UpdateHelper {
    private Context mContext;
    private UpgradeInfo upgradeInfo;

    public UpdateHelper(Context mContext) {
        this.mContext = mContext;
    }

    public void doAutoUpdate() {
        Beta.checkUpgrade(false, false);
    }

    private void doUpdate(String log) throws Exception {
        if (TextUtils.isEmpty(upgradeInfo.apkUrl)) return;
        if (NetUtils.isWifi(mContext)) {
            mandatoryUpdate(log);
        } else {
            if (!SystemUtils.withinOneDay(SPHelper.getLong(mContext, SPConstant.LAST_SHOW_UPDATE_TIME, 0)))
                optionalUpdate(log);
        }
    }

    private void optionalUpdate(String log) {
        UpdateDialog dialog = new UpdateDialog(mContext, R.style.Dialog);
        dialog.setOnUpdateClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onUpdateClick();
            }
        });
        dialog.setOnLaterUpdateClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SPHelper.putLong(mContext, SPConstant.LAST_SHOW_UPDATE_TIME, SystemUtils.getSystemTimeLongType());
            }
        });
        dialog.setLog(log);
        dialog.setCancelable(false);
        dialog.showUpdateLaterBtn(true);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void mandatoryUpdate(String log) {
        UpdateDialog dialog = new UpdateDialog(mContext, R.style.Dialog);
        dialog.setOnUpdateClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onUpdateClick();
            }
        });
        dialog.setLog(log);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void onUpdateClick() {
        try {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/BCY_UPDATE-" +
                    SystemUtils.getAppVersionCode(mContext, mContext.getPackageName()) + ".apk");
            if (file.exists() && upgradeInfo.apkMd5.equals(FileUtils.calculateMD5(file))) {
                Intent mIntent = new Intent();
                mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mIntent.setAction(Intent.ACTION_VIEW);
                mIntent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "application/vnd.android.package-archive");
                mContext.getApplicationContext().startActivity(mIntent);
            } else {
                DownloadManager downloadManager = (DownloadManager) mContext.getSystemService(
                        BaseApplication.DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(upgradeInfo.apkUrl));
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "BCY_UPDATE-" +
                        SystemUtils.getAppVersionCode(mContext, mContext.getPackageName()) + ".apk");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                downloadManager.enqueue(request);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SPHelper.putLong(mContext, SPConstant.LAST_SHOW_UPDATE_TIME, 0);
        }
    }
}